import axios from 'axios'
import storage from '../libs/storage'
import { message } from 'antd'

const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 10000
})

service.interceptors.request.use(
  (config) => {
    config.headers.Authorization = 'Bearer ' + storage.get('token')

    if (config.method.toLocaleUpperCase() === 'GET') {
      config.url += `?n=${Date.now()}`
    }
    return config
  },
  error => {
    // do something with request error
    if (import.meta.env.MODE === 'development') {
      console.log(error) // for debug
    }
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  (response) => {
    const res = response.data

    if (res.code === 200) {
      if (response.config.method.toLocaleUpperCase() !== 'GET') {
        message.open({
          type: 'success',
          content: res.message
        })
      }
      return res
    }
    console.error(res)
    message.open({
      type: 'error',
      content: res.message
    })
    return Promise.reject(res.message)

  },
  error => {
    if (import.meta.env.MODE === 'development') {
      console.log(error) // for debug
    }
    if (error.status === 401) {
      storage.remove('token')
      storage.remove('user')
      window.location.href = `/login?redirect=${location.pathname}`
    }

    message.open({
      type: 'error',
      content: error.message
    })
    return Promise.reject(error)
  }
)

export default service